<?php

namespace App\Http\Controller;

use App\Http\Middleware\ControllerMiddleware;
use App\Http\MyValidator\ProductValidator;
use App\lib\MyRequest;
use App\lib\ProductEntity;
use Swoft\Context\Context;
use Swoft\Db\DB;
use Swoft\Http\Message\ContentType;
use Swoft\Http\Message\Response;
use Swoft\Http\Server\Annotation\Mapping\Controller;
use Swoft\Http\Server\Annotation\Mapping\Middleware;
use Swoft\Http\Server\Annotation\Mapping\RequestMapping;
use  Swoft\Http\Server\Annotation\Mapping\RequestMethod;
use Swoft\Validator\Annotation\Mapping\Validate;
use Swoft\Validator\Validator;

/**
 * 商品模块
 * @Controller(prefix="/product")
 * @Middleware(ControllerMiddleware::class)
 */
class Product
{
    /**
     * @RequestMapping(route="/product",method={RequestMethod::GET})
     */
    public function prod_list()
    {
        $req = Context::get()->getRequest();
        $res = Context::get()->getResponse();
        return $res->withContentType("application/json")
            ->withData([NewProduct(101, "java入门")
                , NewProduct(102, "PHP入门")]);
    }

    /**
     * 添加 @ 是注解验证的形式
     * Validate(validator="product")
     * @RequestMapping(route="{pid}",params={"pid"="\d+"},method={RequestMethod::GET,RequestMethod::POST})
     */
    public function prod_detail(int $pid)
    {
        // $p = NewProduct($pid, "测试商品-链式");

        $product = DB::db('db')->selectOne("select * from products where  id = ?", [$pid]);
        var_dump($product);

        ///** @var  $product ProductEntity */
        //$product = jsonForObject(ProductEntity::class);
        //echo $product->getProdName();
        //var_dump($product);

        $my = new MyRequest();
        return $my->if(isGet())
            ->then(function () use ($product) {
                return $product;
            })
            ->if(isPost())
            ->then(function () use ($product) {
                // 这里是非注解验证的方法
                $data = context()->getRequest()->input();
                $result = validate($data, 'product');
                return $product;
            })
            ->getResult();

//          if(isGet()){
//              return $p;
//          }
//          else if(isPost()) {
//              $p->pname="修改商品".request()->post('title',"none");
//              return $p;
//          }


    }

}
